const cors = require("cors");
const express = require("express");
const createCsvWriter = require("csv-writer").createObjectCsvWriter;

const app = express();
const port = 3022;

let csvWriter = null;
let curFileName = "";

// 创建 CSV 写入器
function createCsvInstance(fileName) {
  curFileName = fileName;
  const dirPath = "D:/ZBK";
  // 检查文件夹是否存在，不存在则创建
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath, { recursive: true });
  }
  const filePath = path.join(dirPath, `${curFileName}.csv`);
  // 检查文件是否存在
  csvWriter = createCsvWriter({
    path: filePath, // 输出文件路径
    // 文件不存在时写入表头
    header: [
      { id: "target_time", title: "target_time" },
      { id: "app", title: "app" },
      { id: "event_key", title: "event_key" },
      { id: "data_json", title: "data_json" },
      { id: "ip", title: "ip" },
      { id: "channel", title: "channel" },
      { id: "version", title: "version" },
      { id: "account", title: "account" },
      { id: "device_id", title: "device_id" },
      { id: "display", title: "display" },
    ],
  });
}
// 销毁 CSV 实例
function destoryCsvInstance() {
  csvWriter = null;
}

// 追加数据到 CSV 文件
function addCsvData(fileName, data) {
  if (!csvWriter) return;
  if (!curFileName || curFileName !== fileName) {
    destoryCsvInstance();
    createCsvInstance(fileName);
  }
  data.target_time = data.target_time.toString();
  if (data.data_json) {
    data.data_json = JSON.stringify(data.data_json);
  }
  csvWriter.writeRecords([data]).catch((error) => {
    console.error("CSV 文件写入失败:", error);
  });
}

function createHttpServer() {
  // 解析 JSON 和表单数据（x-www-form-urlencoded）
  app.use(express.json());
  app.use(express.urlencoded({ extended: true }));
  app.use(cors());

  app.post("/createCsvInstance", (req, res) => {
    createCsvInstance(req.body.fileName);
    res.json({ message: "ok" });
  });
  app.post("/destoryCsvInstance", (_, res) => {
    destoryCsvInstance();
    res.json({ message: "ok" });
  });
  app.post("/addCsvData", (req, res) => {
    addCsvData(req.body.fileName, req.body.data);

    res.json({ message: "ok" });
  });

  // 启动服务器
  app.listen(port, () => {
    console.log(`服务器已启动：http://localhost:${port}`);
  });
}

createHttpServer();
